package com.sbx.utils;

import com.sbx.entity.dto.User;
import com.sbx.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class RequestUtil {

    public static HttpServletRequest getRequest() {
        return Optional.ofNullable(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())).orElseThrow(() -> new RuntimeException("未获取到当前请求信息")).getRequest();
    }

    /**
     * 获取Key获取Value
     * @return String
     */
    public static String getHeadKey(String key) {
        String value = RequestUtil.getRequest().getHeader(key);
        if (StringUtils.isEmpty(value)) {
            throw new RuntimeException("无法获取"+key);
        }
        return value;
    }


    public static String getTokenId(){
        String value = RequestUtil.getRequest().getHeader("token");
        if (StringUtils.isEmpty(value)) {
            throw new RuntimeException("无法获取token");
        }
        return value;
    }

    public static User getUserId(UserService userService){
        String value = RequestUtil.getRequest().getHeader("userId");
        if (StringUtils.isEmpty(value)) {
            throw new RuntimeException("无法获取userId");
        }
        return  userService.getUserById(value);
    }
}

